#include "smartconfig_driver.h"
static const int ESPTOUCH_DONE_BIT = BIT1;
static EventGroupHandle_t s_wifi_event_group;

static void smartconfig_event_handler(void* arg, esp_event_base_t event_base,int32_t event_id, void* event_data)
{
    if (event_base == SC_EVENT && event_id == SC_EVENT_SCAN_DONE) 
    {
        printf("Scan done\n");
    } 
    else if (event_base == SC_EVENT && event_id == SC_EVENT_FOUND_CHANNEL) 
    {
        printf("Found channel\n");
    } 
    else if (event_base == SC_EVENT && event_id == SC_EVENT_GOT_SSID_PSWD) 
    {
        printf("Got SSID and passwor\n");

        smartconfig_event_got_ssid_pswd_t *evt = (smartconfig_event_got_ssid_pswd_t *)event_data;
        wifi_config_t wifi_config;
        uint8_t ssid[33] = { 0 };
        uint8_t password[65] = { 0 };
        uint8_t rvd_data[33] = { 0 };

        bzero(&wifi_config, sizeof(wifi_config_t));
        memcpy(wifi_config.sta.ssid, evt->ssid, sizeof(wifi_config.sta.ssid));
        memcpy(wifi_config.sta.password, evt->password, sizeof(wifi_config.sta.password));
        wifi_config.sta.bssid_set = evt->bssid_set;
        if (wifi_config.sta.bssid_set == true) 
        {
            memcpy(wifi_config.sta.bssid, evt->bssid, sizeof(wifi_config.sta.bssid));
        }

        memcpy(ssid, evt->ssid, sizeof(evt->ssid));
        memcpy(password, evt->password, sizeof(evt->password));
        printf("SSID:%s\n", ssid);
        printf("PASSWORD:%s\n", password);
        
        wifi_sta_set_cfg((char *)ssid,(char *)password); //设置账号密码

        if (evt->type == SC_TYPE_ESPTOUCH_V2) 
        {
            ESP_ERROR_CHECK( esp_smartconfig_get_rvd_data(rvd_data, sizeof(rvd_data)) );
            printf("RVD_DATA:");
            for (int i=0; i<33; i++) 
            {
                printf("%02x ", rvd_data[i]);
            }
            printf("\n");
        }
        wifi_sta_connection(); //连接WiFi
    } 
    else if 
    (event_base == SC_EVENT && event_id == SC_EVENT_SEND_ACK_DONE) {
        xEventGroupSetBits(s_wifi_event_group, ESPTOUCH_DONE_BIT);
    }
}


static void smartconfig_example_task(void * parm)
{
    EventBits_t uxBits;
    ESP_ERROR_CHECK( esp_smartconfig_set_type(SC_TYPE_ESPTOUCH) );
    smartconfig_start_config_t cfg = SMARTCONFIG_START_CONFIG_DEFAULT();
    ESP_ERROR_CHECK( esp_smartconfig_start(&cfg) );
    while (1) 
    {
        uxBits = xEventGroupWaitBits(s_wifi_event_group,ESPTOUCH_DONE_BIT, true, false, portMAX_DELAY);



        if(uxBits&ESPTOUCH_DONE_BIT) 
        {
            printf("smartconfig over\n");
            esp_smartconfig_stop();
            vTaskDelete(NULL);
        }
    }
}


void init_smartconfig_task()
{
    xTaskCreate(smartconfig_example_task, "smartconfig_example_task", 4096, NULL,TASK_PROP_NET, NULL);
}


void smartconfig_enable()
{
    s_wifi_event_group = xEventGroupCreate();
    ESP_ERROR_CHECK( esp_event_handler_register(SC_EVENT,ESP_EVENT_ANY_ID,&smartconfig_event_handler,NULL) );
    init_smartconfig_task();
}
